package com.seu.me.thread.day2.conn011;

/**
 * 利用了classloader的机制来保证初始化instance时只有一个线程，所以也是线程安全的，
 * 同时没有性能损耗，所以一般我倾向于使用这一种。
 * <p>
 * Created by feihu.Mr on 2017/11/19.
 */
public class Singleton {
    private Singleton() {
    }

    private static class InnerSingleton {
        private static final Singleton single = new Singleton();
    }

    public static final Singleton getInstance() {
        return InnerSingleton.single;
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " : " + Singleton.getInstance().hashCode());
            }
        }, "t1");

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " : " + Singleton.getInstance().hashCode());
            }
        }, "t2");

        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " : " + Singleton.getInstance().hashCode());
            }
        }, "t3");

        t1.start();
        t2.start();
        t3.start();
    }
}
